package com.vina.web.servlet;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import com.vina.domain.Blog;
import com.vina.persistence.PMF;
import com.vina.utils.Utils;
import com.vina.web.thymeleaf.TemplateEngineUtil;

public class BlogListServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
private static TemplateEngine te;
	
	public BlogListServlet(){
		super();
		te = TemplateEngineUtil.getInstance().getEngine();
	}
	
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doService(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doService(request, response);
    }

    protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	Query q = pm.newQuery(Blog.class);
        q.setOrdering("date desc");
        
        List<Blog> results = null;
        
        try{
     	   results = (List<Blog>)q.execute();
     	   System.out.println("------BlogList------");
     	   for(Blog b : results){
     		   System.out.println(b.toString());
     	   }
	       WebContext ctx = new WebContext(request, getServletContext(), request.getLocale());
	       ctx.setVariable("urlRelativePath",Utils.getRelativeURLPath("blog/list"));
	       ctx.setVariable("blogs", results);
	       response.setCharacterEncoding("utf-8"); //key!!
	       te.process("blog/list", ctx, response.getWriter());
        }finally{
     	   q.closeAll();
     	   pm.close();
        }
    }

}
